package com.sun.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.common.core.entity.BaseDO;
import com.sun.common.core.model.dto.DataDTO;
import com.sun.common.core.model.query.PageQuery;
import com.sun.common.core.utils.SimpleConverter;
import com.sun.service.dao.TmVhcVehicleMovementDao;
import com.sun.service.dto.TmVhcVehicleMovementReportPointDto;
import com.sun.service.dto.TmVhcVehicleMovementReportPointExcelExportDto;
import com.sun.service.dto.TmVhcVehicleMovementReportPointQuery;
import com.sun.service.entity.TmVhcVehicleMovementDo;
import com.sun.service.entity.TrScanRecordDo;
import com.sun.service.service.TmVhcVehicleMovementService;
import com.sun.service.service.TrScanRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
@Service
public class TmVhcVehicleMovementServiceImpl extends ServiceImpl<TmVhcVehicleMovementDao, TmVhcVehicleMovementDo> implements TmVhcVehicleMovementService {

    @Resource
    private TmVhcVehicleMovementDao tmVhcVehicleMovementDao;


    @Resource
    private TrScanRecordService trScanRecordService;

    public static long startTime;


    /**
     * 整车过点列表查询分页
     *
     * @param pageQuery 入参
     * @param query     入参
     * @return
     * @author hxy0098
     */
    @Override
    public DataDTO<List<TmVhcVehicleMovementReportPointDto>> queryReportPoint(PageQuery pageQuery, TmVhcVehicleMovementReportPointQuery query) {
        startTime = System.currentTimeMillis();
        IPage<TmVhcVehicleMovementReportPointDto> doPage = tmVhcVehicleMovementDao.queryReportPoint(new Page<>(pageQuery.getCurrent(), pageQuery.getPageSize()), doOrganizeQueryData(query));
        System.out.println("分页查询时间" + (System.currentTimeMillis() - startTime));
        System.out.println("数据量大小为: " + doPage.getRecords().size());
        return new DataDTO<>(doOrganizeReturnData(doPage.getRecords()), doPage);
    }

    /**
     * 整车过点查询报表结果导出
     *
     * @param query
     * @return
     * @author hxy0098
     */
    @Override
    public List<TmVhcVehicleMovementReportPointExcelExportDto> exportReportPoint(TmVhcVehicleMovementReportPointQuery query) {
        List<TmVhcVehicleMovementReportPointDto> dtoList = tmVhcVehicleMovementDao.queryReportPoint(doOrganizeQueryData(query));
        return SimpleConverter.convert(doOrganizeReturnData(dtoList), TmVhcVehicleMovementReportPointExcelExportDto.class);
    }

    /**
     * 整车过点查询返回值整理
     *
     * @param dtoList
     * @return
     * @author hxy0098
     */
    private List<TmVhcVehicleMovementReportPointDto> doOrganizeReturnData(List<TmVhcVehicleMovementReportPointDto> dtoList) {
        if (CollUtil.isEmpty(dtoList)) return new ArrayList<>();

        // 其他过点时间
        List<String> idList = dtoList.stream().map(TmVhcVehicleMovementReportPointDto::getTvvmId).collect(Collectors.toList());
        List<TmVhcVehicleMovementDo> doList = list(Wrappers.lambdaQuery(TmVhcVehicleMovementDo.class)
                .select(BaseDO::getId, TmVhcVehicleMovementDo::getNodeNature, TmVhcVehicleMovementDo::getInputTime)
                .notIn(TmVhcVehicleMovementDo::getNodeNature, "0", "Key_Uloc_Type_OTHER")
                .isNotNull(TmVhcVehicleMovementDo::getInputTime)
                .isNotNull(TmVhcVehicleMovementDo::getNodeNature)
                .in(BaseDO::getId, idList));

        System.out.println("其他过点查询时间" + (System.currentTimeMillis() - startTime));

        Map<String, Map<String, Date>> map = doList.stream().collect(Collectors.groupingBy(BaseDO::getId, Collectors.toMap(TmVhcVehicleMovementDo::getNodeNature, TmVhcVehicleMovementDo::getInputTime, (existing, replacement) -> existing.compareTo(replacement) > 0 ? existing : replacement)));
        System.out.println("其他过点数据整理时间" + (System.currentTimeMillis() - startTime));

        // 发动机上线时间 动力总成合装时间
        List<String> vinList = dtoList.stream().map(TmVhcVehicleMovementReportPointDto::getVin).collect(Collectors.toList());
        List<TrScanRecordDo> recordList =trScanRecordService.list(Wrappers.lambdaQuery(TrScanRecordDo.class)
                        .select(TrScanRecordDo::getScanType, TrScanRecordDo::getVin, TrScanRecordDo::getScanTime)
                        .isNotNull(TrScanRecordDo::getVin)
                        .isNotNull(TrScanRecordDo::getScanType)
                        .isNotNull(TrScanRecordDo::getScanTime)
                        .in(TrScanRecordDo::getScanType, Arrays.asList("Key_Uloc_Function_10", "Key_Uloc_Function_1"))
                        .in(TrScanRecordDo::getVin, vinList));
        System.out.println(" 发动机上线时间 动力总成合装时间 查询时间" + (System.currentTimeMillis() - startTime));
        Map<String, Map<String, Date>> recordMap = recordList.stream().collect(Collectors.groupingBy(TrScanRecordDo::getVin, Collectors.toMap(TrScanRecordDo::getScanType, TrScanRecordDo::getScanTime, (existing, replacement) -> existing.compareTo(replacement) > 0 ? existing : replacement)));
        System.out.println(" 发动机上线时间 动力总成合装时间 数据整理时间" + (System.currentTimeMillis() - startTime));

        // 数据赋值
        dtoList.stream()
                .parallel()
                .forEach(dto -> {
                    Map<String, Date> tvvMap = map.get(dto.getTvvmId());
                    Map<String, Date> recMap = recordMap.getOrDefault(dto.getVin(), new HashMap<>());
                    dto.setHz10Time(tvvMap.get("Key_Uloc_Type_HZ10"));
                    dto.setHz20Time(tvvMap.get("Key_Uloc_Type_HZ20"));
                    dto.setTz10Time(tvvMap.get("Key_Uloc_Type_TZ10"));
                    dto.setTz20Time(tvvMap.get("Key_Uloc_Type_TZ20"));
                    dto.setPbsTime(tvvMap.get("Key_Uloc_Type_PBS"));
                    dto.setZz10Time(tvvMap.get("Key_Uloc_Type_ZZ10"));
                    dto.setZz20Time(tvvMap.get("Key_Uloc_Type_ZZ20"));
                    dto.setZz30Time(tvvMap.get("Key_Uloc_Type_ZZ30"));
                    dto.setEngTime(recMap.get("Key_Uloc_Function_10"));
                    dto.setApTime(recMap.get("Key_Uloc_Function_1"));
//                    dto.setFc04Desc(bizDictMap.get(dto.getFc04()));
//                    dto.setTargetCountry(countryDictMap.get(dto.getTargetCountry()));
                    switch (dto.getIsAllocation()) {
                        case "0":
                            dto.setIsAllocation("不调拨");
                            break;
                        case "1":
                            dto.setIsAllocation("焊装调拨");
                            break;
                        case "2":
                            dto.setIsAllocation("涂装调拨");
                        case "7":
                            dto.setIsAllocation("焊出总入");
                            break;
                        default:
                            dto.setIsAllocation("不识别");
                    }
                });
        System.out.println("数据整理时间" + (System.currentTimeMillis() - startTime));
        return dtoList;
    }

    /**
     * 整车过点查询查询值处理
     *
     * @param query
     * @return
     * @author hxy0098
     */
    private TmVhcVehicleMovementReportPointQuery doOrganizeQueryData(TmVhcVehicleMovementReportPointQuery query) {
        // 解析vin
        if (StrUtil.isNotBlank(query.getVin())) {
            query.setVin(query.getVin().replaceAll(",", "|"));
        }

        // 解析物料号
        if (StrUtil.isNotBlank(query.getMaterialNo())) {
            query.setMaterialNoList(Arrays.stream(query.getMaterialNo().split(",")).collect(Collectors.toList()));
        }
        return query;
    }

}
